<?php
namespace app\admin\controller;
use think\Controller;
use think\Db;
use think\Session;
use app\admin\model\Admin as AdminModel;
//登录
class Login extends Controller
{
	//页面
    public function index()
    {
        $client = Db::name('client')->where('id', 1)->find();
        $this->assign('client',$client);
    	return $this->fetch();
    }
    //提交登录
    public function login()
    {
    	$status = 0;
        $msg= '登录失败';
        $data = $this -> request -> param();
        $userName = $data['username'];
        $password = md5(trim($data['password']));
        if (empty($userName)) {
            return ['status'=> $status, 'msg'=> '用户名不能为空'];
        }
        if (empty($password)) {
            return ['status'=> $status, 'msg'=> '密码不能为空'];
        }
        if(!captcha_check($data['code'])){
            //验证码错误
            $msg='验证码错误';
            return ['status'=> $status, 'msg'=> $msg];
        }
        $map = ['username'=>$userName];
        $admin = AdminModel::get($map);
        $map1 = ['realname'=>$userName];
        $admin1 = AdminModel::get($map1);
         if (is_null($admin)||empty($admin)){

            if (is_null($admin1)||empty($admin1)){
                 $msg = '用户名不正确';
            }elseif ($admin1['password'] != $password) {
                $msg = '密码不正确';
            }else{
                 $admin= $admin1;
                 //更新管理员状态
                 $param = [
                     'loginnum' => $admin['loginnum'] + 1,
                     'last_login_ip' => request()->ip(),
                     'last_login_time' => time()
                 ];

                 Db::name('admin')->where('id', $admin['id'])->update($param);
                 Session::set('user_id',$admin['id']);
                 Session::set('user_info',$admin->toArray());
                 //管理员日志
                 adminlog();
                 
                 //返回信息
                 $status = 1;
                 $msg = '登录成功';
             }


        }elseif ($admin['password'] != $password) {
            $msg = '密码不正确';
        } else {

            //更新管理员状态
            $param = [
                'loginnum' => $admin['loginnum'] + 1,
                'last_login_ip' => request()->ip(),
                'last_login_time' => time()
            ];

            Db::name('admin')->where('id', $admin['id'])->update($param);          
            Session::set('user_id',$admin['id']);
            Session::set('user_info',$admin->toArray());
          
            //管理员日志
            adminlog();
            //返回信息
            $status = 1;
            $msg = '登录成功';
        }
        return ['status'=> $status, 'msg'=> $msg];
    }

     //退出登录
    public function logout()
    {

        //删除当前用户session值
        Session::delete('user_id');
        Session::delete('user_info');
        //执行成功,并返回登录界面
        //$this->redirect('index/index');
         $this->redirect('login/index');
    }
}
